package com.bac.rentmap.ad.flat.user.view;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Required;

/**
 * Updating datatastore on each flat ad view is to expensive. Thus we collect view statistics update requests in this class.
 * As soon as we collect more than <code>threshold</code> requests we flush all collected statistics to the underlying <code>viewStatisticsManager</code>
 * implementation.
 * 
 * @author Andrew Osipenko
 */
public class BulkIncrementViewStatisticsManager implements
        ViewStatisticsManager, DisposableBean {
    private static final Logger log = Logger
            .getLogger(BulkIncrementViewStatisticsManager.class.getName());

    private int threshold;
    private ViewStatisticsManager viewStatisticsManager;
    private AtomicInteger postponedIncRequestCount = new AtomicInteger();
    private Map<Long, Integer> postponedIncRequests = Collections.synchronizedMap(new HashMap<Long, Integer>());
    

    @Override
    public void inc(long flatAdId, int count) {
        Integer flatAdIncRequestCount = postponedIncRequests.get(flatAdId);
        if(flatAdIncRequestCount ==  null)
            flatAdIncRequestCount =  0;
        postponedIncRequests.put(flatAdId, flatAdIncRequestCount + 1);
        if(postponedIncRequestCount.incrementAndGet() > threshold){
            flushPostponedIncRequests();
        }
    }
    
    private synchronized void flushPostponedIncRequests(){
        postponedIncRequestCount.set(0);
        log.fine("Flushing postponed inc requests");
        Map<Long, Integer> postponedIncRequestsCopy = postponedIncRequests;
        postponedIncRequests = Collections.synchronizedMap(new HashMap<Long, Integer>());
        for (Map.Entry<Long, Integer> entry : postponedIncRequestsCopy.entrySet()) {
            viewStatisticsManager.inc(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public List<ViewStatistics> load(long flatAdId) {
        return viewStatisticsManager.load(flatAdId);
    }

    @Override
    public int deleteOldStatistics() {
        return viewStatisticsManager.deleteOldStatistics();
    }
    
    @Override
    public void destroy() throws Exception {
        flushPostponedIncRequests();
    }

    @Required
    public void setThreshold(int threshold) {
        if(threshold < 1)
            throw new IllegalArgumentException();
        this.threshold = threshold;
    }

    @Required
    public void setViewStatisticsManager(ViewStatisticsManager viewStatisticsManager) {
        this.viewStatisticsManager = viewStatisticsManager;
    }
}
